package com.koron.car.web.costregister.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.alibaba.excel.read.listener.ReadListener;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.car.config.Constants;
import com.koron.car.web.carledger.bean.vo.CarVO;
import com.koron.car.web.carledger.mapper.CarMapper;
import com.koron.car.web.common.CommonUtils;
import com.koron.car.web.costregister.bean.entity.CostRegister;
import com.koron.car.web.costregister.bean.vo.RepairFeeExcel;
import com.koron.car.web.costregister.mapper.CostRegisterMapper;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.StringUtils;
import lombok.SneakyThrows;
import org.apache.commons.lang.math.NumberUtils;
import org.koron.ebs.mybatis.SessionFactory;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class RepairFeeStorageListener implements ReadListener<RepairFeeExcel> {

    private SessionFactory factory;
    private static final List<CostRegister> LIST = new ArrayList<>();
    private static final int BATCH_COUNT = 50;

    public RepairFeeStorageListener(SessionFactory factory) {
        this.factory = factory;
    }

    @SneakyThrows
    @Override
    public void invoke(RepairFeeExcel repairFeeExcel, AnalysisContext analysisContext) {
        EamUser eamUser = ThreadLocalContext.get();
        String licPlateNum = repairFeeExcel.getLicPlateNum();
        CarMapper carMapper = factory.getMapper(CarMapper.class);
        CarVO carVO = carMapper.queryByPlateNum(licPlateNum);
        CostRegister costRegister = new CostRegister();
        if (Objects.nonNull(carVO)) {
            costRegister.setMotorcade(carVO.getMotorcade() == null ? null : carVO.getMotorcade());
            costRegister.setCarId(carVO.getId());
        }
        CommonUtils.update(costRegister, eamUser);
        costRegister.setDeptId(eamUser.getOrgId());
        costRegister.setId(CodeTools.getCode32());
        costRegister.setCostType(Constants.FeeType.MATAINFEE);
        costRegister.setState(Constants.FeeState.FINISH);
        costRegister.setRemark(repairFeeExcel.getRemark());
        costRegister.setCost(repairFeeExcel.getRepairFee());
        costRegister.setStartTime(convertTime(repairFeeExcel.getRepairTime()));
        costRegister.setLicPlateNum(repairFeeExcel.getLicPlateNum());
        LIST.add(costRegister);
        if (LIST.size() >= BATCH_COUNT) {
            saveData(LIST);
            LIST.clear();
        }
    }

    private Date convertTime(String repairTime) {
        if (StringUtils.isBlank(repairTime)){
            return new Date();
        }
        String result = repairTime.replace(".", "-");
        Date parse = null;
        try {
            parse = new SimpleDateFormat("yyyy-MM-dd").parse(result);
        } catch (ParseException e) {
            parse = null;
        }
        return parse;
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (LIST.size() == 0) {
            return;
        }
        saveData(LIST);

        // 保存完之后清空集合数据
        if (LIST.size() > 0) {
            LIST.clear();
        }
    }

    private void saveData(List<CostRegister> list) {
        CostRegisterMapper costRegisterMapper = factory.getMapper(CostRegisterMapper.class);
        costRegisterMapper.insertBatch(list);
    }

    public RepairFeeStorageListener read(String filePath, int headNum) {
        EasyExcel.read(filePath, this).head(RepairFeeExcel.class).autoCloseStream(true
        ).autoTrim(true).ignoreEmptyRow(true).sheet()
                // 这里可以设置1，因为头就是一行。如果多行头，可以设置其他值。不传入也可以，因为默认会根据DemoData 来解析，他没有指定头，也就是默认1行
                .headRowNumber(Math.max(headNum, NumberUtils.BYTE_ZERO)).doRead();
        return this;
    }

    public RepairFeeStorageListener read(InputStream inputStream, int headNum) {
        EasyExcel.read(inputStream, this)
                .extraRead(CellExtraTypeEnum.MERGE)
                .head(RepairFeeExcel.class)
                .autoCloseStream(true)
                .autoTrim(true)
                .ignoreEmptyRow(true)
                .sheet()
                // 这里可以设置1，因为头就是一行。如果多行头，可以设置其他值。不传入也可以，因为默认会根据DemoData 来解析，他没有指定头，也就是默认1行
                .headRowNumber(Math.max(headNum, NumberUtils.BYTE_ZERO)).doRead();
        return this;
    }

}
